<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h } from "vue";
import ProFrom from "@/components/ProFrom/ProFrom.vue";
import ProTable from "@/components/ProTable";
import { UploadBtn } from "@/components/Upload";
import { message, Modal } from "ant-design-vue";
import useModal from "@/hooks/useModal";
import { queryFormMap, editFormMap, detailMap } from "./form";
import { columns } from "./table";
import { setBaseApi, get, post, del } from "@/api/http";

setBaseApi("/watch/Schedule/");

const queryForm = reactive({});
const querying = ref<boolean>(false);
const queryFormRef = ref<InstanceType<typeof ProFrom>>();

const tableRef = ref<InstanceType<typeof ProTable>>();

const tableData = reactive({
  list: [],
  total: 0,
});
const selected = computed(() => tableRef.value?.selectedRowKeys);

onMounted(() => handleQuery());

const handleQuery = () => {
  queryFormRef.value
    ?.verify()
    .then(async (query: any) => {
      const pageParams = tableRef.value?.pageOption;
      const params = { ...query, ...pageParams };
      // console.log(params);
      // return;
      get("page", params, "", querying).then(({ list, totalCount }) => {
        tableData.list = list;
        tableRef.value?.updateTotal(totalCount);
      });
    })
    .catch((err: any) => {});
};

const editFormRef = ref<InstanceType<typeof ProFrom>>();
const editModel = reactive({
  open: false,
  editAble: true,
  title: "编辑",
  row: {} as any,
});

const onEdit = () => {
  // if (editModel.title == "详情") return (editModel.open = false);
  editFormRef.value?.verify().then((data: any) => {
    const id = editModel.row?.id;
    data.forecastDuty = data?.forecastDuty?.join(",");
    data.hangZhou = data?.hangZhou?.join(",");
    data.iformationDuty = data?.iformationDuty?.join(",");
    data.ningBo = data?.ningBo?.join(",");
    data.officerDuty = data?.officerDuty?.join(",");
    data.officerMember = data?.officerMember?.join(",");
    data.reportDuty = data?.reportDuty?.join(",");
    data.shiftLeader = data?.shiftLeader?.join(",");
    data.wenZhou = data?.wenZhou?.join(",");
    // console.log(data);
    // return;
    post("saveOrUpdate", [{ ...data, id }], "提交").then(() => {
      // 注释下面代码 以便新增排班
      handleQuery();
      editModel.open = false;
    });
  });
};

const handleEdit = (row?: any) => {
  console.log(row);

  // const modal = useModal(
  //   row ? "编辑" : "新增",
  //   h(ProFrom, {
  //     ref: "editFormRef",
  //     readonly: false,
  //     mapping: editFormMap,
  //     modelValue: editModel.row,
  //   }),
  //   onEdit
  // );
  // return;
  editModel.open = true;
  editModel.editAble = true;
  editModel.title = row ? "编辑" : "新增";
  editModel.row = row
    ? {
        ...row,
        forecastDuty: row.forecastDuty.split(","),
        hangZhou: row.hangZhou.split(","),
        iformationDuty: row.iformationDuty.split(","),
        ningBo: row.ningBo.split(","),
        officerDuty: row.officerDuty.split(","),
        officerMember: row.officerMember.split(","),
        reportDuty: row.reportDuty.split(","),
        shiftLeader: row.shiftLeader.split(","),
        wenZhou: row.wenZhou.split(","),
      }
    : {};
};
// const handleDetail = (row: any) => {
//   editModel.open = true;
//   editModel.editAble = false;
//   editModel.title = "详情";
//   editModel.row = row;
// };

const detail = reactive({
  open: false,
  data: {},
});

const detailFormMap = ref(detailMap);

const handleDetail = async (current: any) => {
  const { reponStatus, id, dutyDate } = current;
  const { watchStaffDtoList } = await get("info", { id });
  let reponList = [];
  // 应急响应状态时
  if (["1", "2", "3", "4"].includes(reponStatus)) {
    // 详情表单展示响应人员表格
    detailFormMap.value = detailFormMap.value.concat([
      {
        label: "响应人员",
        type: "table",
        prop: "reponList",
        columns: [
          {
            label: "姓名",
            prop: "name",
          },
          {
            label: "职位",
            prop: "position",
          },
          {
            label: "联系方式",
            prop: "phone",
          },
          {
            label: "岗位职责",
            prop: "job",
          },
        ],
      },
    ]);
    reponList = await get("getResponseList", { reponStatus });
  }

  detail.data = {
    dutyDate,
    phone: "1111-0000-000",
    reponStatus,
    watchStaffDtoList,
    reponList,
  };

  detail.open = true;
};

const onDrawerClose = () => (detailFormMap.value = editFormMap);

const handleDeleteAll = () => {
  console.log(selected.value);
};

const onImport = (url: string) => {
  console.log(url);
  handleQuery();
};
</script>

<template>
  <section class="page">
    <header>
      <ProFrom
        layout="inline"
        ref="queryFormRef"
        :mapping="queryFormMap"
        :model-value="queryForm"
        :defaultCol="4"
        @submit="handleQuery()"
      >
        <ProButton
          @click="() => queryFormRef?.reset()"
          text="重置"
          icon="redoOutlined"
          class="mr-15px"
        />
        <ProButton
          @click="handleQuery"
          type="primary"
          text="查询"
          :loading="querying"
          icon="SearchOutlined"
        />
      </ProFrom>
    </header>
    <main>
      <nav>
        <ProButton
          @click="handleEdit()"
          type="primary"
          text="新增"
          icon="plusOutlined"
        />

        <ProButton
          @click="handleQuery()"
          text="刷新"
          :loading="querying"
          icon="redoOutlined"
        />

        <!-- <ProButton
          @click="handleDeleteAll"
          type="danger"
          text="删除"
          :disabled="!selected?.length"
          icon="deleteOutlined"
        /> -->

        <!-- <UploadBtn @ok="onImport" /> -->
      </nav>

      <!-- :mapping="editFormMap" -->
      <ProTable
        ref="tableRef"
        :data="tableData.list"
        :columns="columns"
        :operate="{
          编辑: handleEdit,
          详情: handleDetail,
          删除: 'delete',
        }"
        :scroll="{ y: 1000 }"
        @afterOperate="handleQuery"
      >
      </ProTable>
    </main>

    <!-- 编辑弹框 -->
    <a-modal
      centered
      destroyOnClose
      v-model:visible="editModel.open"
      :title="editModel.title"
      @ok="onEdit"
      :okText="editModel.editAble ? '提交' : '关闭'"
    >
      <div class="max-h-60vh overflow-y-scroll">
        <ProFrom
          ref="editFormRef"
          :mapping="editFormMap"
          :model-value="editModel.row"
          :readonly="!editModel.editAble"
        >
        </ProFrom>
      </div>
    </a-modal>

    <!-- 详情抽屉 -->

    <a-drawer
      v-model:visible="detail.open"
      @close="onDrawerClose"
      destroyOnClose
      title="详情"
      width="780"
    >
      <ProFrom
        ref="editFormRef"
        :mapping="detailFormMap"
        :model-value="detail.data"
        :readonly="true"
      />
    </a-drawer>
  </section>
</template>

<style lang="less" scoped></style>
